/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FuInsertPanel.java
 *
 * Created on 27/11/2011, 22:20:15
 */
package proj5labbd.graphics.funcionario;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class FuInsertPanel extends OperationPanel {

    /** Creates new form FuInsertPanel */
    public FuInsertPanel(FuncionarioFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbtInsert.addActionListener(new FuncionarioAction());
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnInsert = new javax.swing.JPanel();
        jlbCPF = new javax.swing.JLabel();
        jftxtCPF = new javax.swing.JFormattedTextField();
        jlbNome = new javax.swing.JLabel();
        jtxtNome = new javax.swing.JTextField();
        jlbTipo = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbInsert = new javax.swing.JTable();
        jlbDate = new javax.swing.JLabel();
        jftxtDate = new javax.swing.JFormattedTextField();
        jtxtSalario = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jbtInsert = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Inserção"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnInsert.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de inserção"));

        jlbCPF.setText("CPF");

        try {
            jftxtCPF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtCPF.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        jlbNome.setText("Nome Completo");

        jlbTipo.setText("Tipo de funcionário");

        jtbInsert.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbInsert);

        jlbDate.setText("Data de nascimento");

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        jLabel1.setText("Salário");

        javax.swing.GroupLayout jpnInsertLayout = new javax.swing.GroupLayout(jpnInsert);
        jpnInsert.setLayout(jpnInsertLayout);
        jpnInsertLayout.setHorizontalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 406, Short.MAX_VALUE)
                    .addGroup(jpnInsertLayout.createSequentialGroup()
                        .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbTipo)
                            .addGroup(jpnInsertLayout.createSequentialGroup()
                                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(jtxtNome, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jftxtCPF, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE))
                                    .addComponent(jlbCPF)
                                    .addComponent(jlbNome))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jlbDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jtxtSalario)
                                    .addComponent(jftxtDate, javax.swing.GroupLayout.DEFAULT_SIZE, 123, Short.MAX_VALUE)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                        .addContainerGap(77, Short.MAX_VALUE))))
        );
        jpnInsertLayout.setVerticalGroup(
            jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnInsertLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbCPF)
                    .addComponent(jlbDate))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jftxtCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbNome)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnInsertLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtSalario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbTipo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jbtInsert.setText("Inserir");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpnInsert, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(12, 12, 12))
                    .addComponent(jbtInsert, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnInsert, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addComponent(jbtInsert))
        );
    }// </editor-fold>//GEN-END:initComponents

    /*
     * Resgata as informações das tabelas que serão exibidas
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações da tabela");
            frame.printException(ex);
        }
    }//GEN-LAST:event_formComponentShown

    /*
     * Trata os eventos do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbInsert.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtInsert;
    private javax.swing.JFormattedTextField jftxtCPF;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JLabel jlbCPF;
    private javax.swing.JLabel jlbDate;
    private javax.swing.JLabel jlbNome;
    private javax.swing.JLabel jlbTipo;
    private javax.swing.JPanel jpnInsert;
    private javax.swing.JTable jtbInsert;
    private javax.swing.JTextField jtxtNome;
    private javax.swing.JTextField jtxtSalario;
    // End of variables declaration//GEN-END:variables
    
    /*
     * Formata a tabela tipoFuncionario
     */
    public void setupTable() throws SQLException {
        String [] fields = {"idTipoFu","salarioBaseTipoFu","descricaoTipoFu"};
        String [][] s = dbInterface.view(fields, null, new String[]{"tipoFuncionario"});
        DefaultTableModel model = new DefaultTableModel(s,new String[]{"ID","Salario","Descrição"});
        jtbInsert.setModel(model);
    }

    class FuncionarioAction implements ActionListener {

        /*
         * Controla os eventos de inserção
         */
        public void actionPerformed(ActionEvent e) {

                if ( jtbInsert.getSelectedRowCount() == 1 && jftxtCPF.getText() != "   .   .   -  " &&
                        jtxtNome.getText().trim() != "" &&
                        jtxtSalario.getText().trim().compareTo("") != 0 
                ) 
                {
                    ArrayList<String> params = new ArrayList<String>();
                    ArrayList<String> fields = new ArrayList<String>();

                    params.add("SEQ_FUNCIONARIO_IDFU.NEXTVAL");
                    fields.add("idFu");
                    params.add("'"+jftxtCPF.getText()+"'");
                    fields.add("cpfFu");
                    params.add("'"+jtxtNome.getText()+"'");
                    fields.add("nomeCompletoFu");

                    if (jftxtDate.getText() != "  -  -    ") {
                        params.add("TO_DATE('"+jftxtDate.getText()+"','DD-MM-YYYY')");
                        fields.add("dataNascimentoFu");
                    }

                    params.add(jtxtSalario.getText());
                    fields.add("salarioFu");
                    
                    params.add((String)jtbInsert.getValueAt(jtbInsert.getSelectedRow(), 0));
                    fields.add("idTipoFu");

                    String [] paramArray = new String[params.size()];
                    String [] fieldArray = new String[fields.size()];

                    params.toArray(paramArray);
                    fields.toArray(fieldArray);
                    try {
                        dbInterface.insert(fieldArray, paramArray, new String[]{"funcionario"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao tentar inserir a tupla.");
                    }

                }
                else if (jtbInsert.getSelectedRowCount() != 1) {
                    JOptionPane.showMessageDialog(null, "Você deve escolher um tipo de funcionário.");
                }
                else if (jtxtNome.getText().trim() == "") {
                    JOptionPane.showMessageDialog(null, "Você deve inserir o nome do funcionário.");
                }

            }
    }
}
